package com.cn.service.impl;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cn.service.DistributedLocker;
@Service("distributedLocker")
public class DistributedLockerImpl implements DistributedLocker {
	@Autowired
	 private RedissonClient redissonClient;
	
	public RLock lock(String lockKey) {
		// TODO Auto-generated method stub
		    RLock lock = redissonClient.getLock(lockKey) ;
		    
	        return lock;
	}

	public RLock lock(String lockKey, int timeout) {
		// TODO Auto-generated method stub
		  RLock lock = redissonClient.getLock(lockKey);
	        lock.lock(timeout, TimeUnit.SECONDS);
	        return lock;
	}

	public RLock lock(String lockKey, TimeUnit unit, int timeout) {
		// TODO Auto-generated method stub
		 RLock lock = redissonClient.getLock(lockKey);
	        lock.lock(timeout, unit);
	        return lock;
	}

	public boolean tryLock(String lockKey, TimeUnit unit, int waitTime,
			int leaseTime) {
		// TODO Auto-generated method stub
		  RLock lock = redissonClient.getLock(lockKey);
	        try {
	            return lock.tryLock(waitTime, leaseTime, unit);
	        } catch (InterruptedException e) {
	            return false;
	        }
	}

	public void unlock(String lockKey) {
		// TODO Auto-generated method stub
		  RLock lock = redissonClient.getLock(lockKey);
	        lock.unlock();
	}

	public void unlock(RLock lock) {
		// TODO Auto-generated method stub
		 lock.unlock();
	}
	 

}
